import spice_activeX, os, sys, atexit

from StdErrOut import SpiceStdErr, SpiceStdOut
from _Command import _Command
from _getpos import _getpos
from _tolerance import _tolerance
from _upperlimit import _upperlimit
from _lowerlimit import _lowerlimit
from _getvar import _getvar
from _twobuttontimed import _twobuttontimed
from vardict import vardict as _vardict
from _finish import _finish


#__all__ = ['utils', 'funcutils', 'oldplot', ]

from _spice_path import spice_path

"""
OUTPUT REDIRECTION BLOCK 1
(Only one of the 3 OUTPUT REDIRECTION BLOCKs should be left uncommented.)

The lines below will redirect stderr and stdout to a logfile
Use this for debugging and comment out the lines below.
The code opens a log file, re-opens stdout without buffering, then redirects.
"""
#so = se = open("C:\\spicetmp\\pyspice.log", 'w', 0)
#sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
#os.dup2(so.fileno(), sys.stdout.fileno())
#os.dup2(se.fileno(), sys.stderr.fileno())


"""
The following lines (before the function definitions) will set up the link
between python and Spice.  This does all the handshaking to ensure the process
is handled correctly.
"""

_spice=spice_activeX.Application()
_scriptglobals=_spice.GetVIReference(spice_path + '\\common\\globals\\script_globals.vi')
_oldpidarray=_scriptglobals.GetControlValue('pids')
_pid=os.getpid()

"""
OUTPUT REDIRECTION BLOCK 2
(Only one of the 3 OUTPUT REDIRECTION BLOCKs should be left uncommented.)

For debugging the link to spice, we can uncomment the sys.stderr and
sys.stdout lines below.  Remember to comment out the equivalent lines
further down
"""
#sys.stderr=SpiceStdErr()
#sys.stdout=SpiceStdOut()

_alreadyexist=_pid in _oldpidarray

if _alreadyexist == 0:
    _execvi=_spice.GetVIReference(spice_path + '\\common\\commands\\exec.vi')
    #The PID doesn't exist - add to global and turn on Successful bit
    #The next line converts the integer to a tuple so that the + operation works
    _pidtuple=_pid,
    _newpidarray=_oldpidarray+_pidtuple
    _scriptglobals.SetControlValue('pids',_newpidarray)
    #Now we get the last script path and set to self.scriptpath
    _scriptpaths=_scriptglobals.GetControlValue('Script Paths')
    _scriptpath=_scriptpaths[len(_scriptpaths)-1]
    _execvi.SetControlValue('Successful',1)
    atexit.register(_finish,spice=_spice,scriptglobals=_scriptglobals,pid=_pid)
else:
    # The PID already exists - don't do any handshaking.
    # We need the self.scriptpath in every instance
    _scriptpaths=_scriptglobals.GetControlValue('Script Paths')
    _scriptpath=_scriptpaths[len(_scriptpaths)-1]


"""
OUTPUT REDIRECTION BLOCK 3
(Only one of the 3 OUTPUT REDIRECTION BLOCKs should be left uncommented.)

The next 2 lines will redirect the stderror and stdout to the logfile
"""
sys.stderr=SpiceStdErr()
sys.stdout=SpiceStdOut()

"""
The next line will load in the variable dictionary needed for the getvar method
"""

_variable_dict=_vardict()

"""
The following defines all the functions which will be available from PySpice
"""

# This function executes a command in Spice

def Command(commandtext):
    _Command(_spice,_pid,_scriptpath,commandtext)
    return


# This function returns the motor position for 'motor'

def getpos(motor):
    motorpos=_getpos(_spice,motor)
    return motorpos

# This function returns the tolerance for 'motor' 

def tolerance(motor):
    tolvalue=_tolerance(_spice,motor)
    return tolvalue

# This function returns the upper limit for 'motor' 

def upperlimit(motor):
    ulimit=_upperlimit(_spice,motor)
    return ulimit

# This function returns the lower limit for 'motor' 

def lowerlimit(motor):
    llimit=_lowerlimit(_spice,motor)
    return llimit

# This is a general method to get a variable.

def getvar(varname):
    var_return=_getvar(_spice,_variable_dict,varname)
    return var_return

def twobuttontimed(string_to_print,timeout,timeoutreturn,truebutton,falsebutton,title):
    buttonpressed=_twobuttontimed(_spice,string_to_print,timeout,timeoutreturn,truebutton,falsebutton,title)
    return buttonpressed
